<?php

/*
	info: 用户控制面板
	date: 2011-12-19
*/

define('PAGESCRIPT', 'my');
define('USER_LOGIN_CHECK', TRUE);
define('AUTH_IDCODE_URL', 'http://www.youdao.com/smartresult-xml/search.s?type=id&q=');

require dirname(__FILE__).'/include/common.inc.php';
global_ConnectDB();
if ($user['base_uid']<=0 || $user['base_type']!=0)
{
	global_ShowMessage("请登录后操作。", WEBURLPATH.'/login.php');
}

//我收藏的优惠券
if ($webglobal['action']=='favorite')
{
	$webrequest['delid'] = isset($webrequest['delid']) ? intval($webrequest['delid']) : 0;
	if ($webrequest['delid'] > 0)
	{
		$webglobal['datainfo'] = $db->GetOne("SELECT * FROM {$webconfig['dbpre']}coupon_favorites WHERE id='{$webrequest['delid']}' AND user_id='{$user['base_uid']}'");
		if (empty($webglobal['datainfo']))
		{
			global_ShowMessage("参数错误。");
		}
		$db->Delete('coupon_favorites', "id='{$webrequest['delid']}'");
		$db->Update('coupon', "favorites_num=favorites_num-1", "id='{$webglobal['datainfo']['coupon_id']}' AND favorites_num>0");
		global_ShowMessage("恭喜您，删除成功。", WEBURLPATH."/my.php?action={$webglobal['action']}&page={$webrequest['page']}");
	}

	$webglobal['perpage'] = 10;
	$tempsearchsql = " WHERE F.user_id='{$user['base_uid']}'";
	$webglobal['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}coupon_favorites F{$tempsearchsql}");
	if ($webglobal['datanum']>0)
	{
		$webglobal['page'] = global_Page($webglobal['datanum'], $webglobal['perpage'], $webrequest['page'], WEBURLPATH."/my.php?action={$webglobal['action']}&page=@@");
		$tempstartnum = ($webrequest['page']-1)*$webglobal['perpage'];
		$query = $db->Query("SELECT F.*,C.name AS c_name,C.image AS c_image FROM {$webconfig['dbpre']}coupon_favorites F LEFT JOIN {$webconfig['dbpre']}coupon C ON F.coupon_id=C.id{$tempsearchsql} ORDER BY F.id DESC LIMIT $tempstartnum, {$webglobal['perpage']}");
		$webglobal['dataarray'] = array();
		while ($tempdata = $db->FetchArray($query))
		{
			$tempdata['addtime_show'] = global_FormatTime($tempdata['addtime']);
			if ($tempdata['c_image']) {
				$tempdata['thumbnail'] = array(
					'big' => getThumbnails($tempdata['c_image'], 'big'),
					'small' => getThumbnails($tempdata['c_image'], 'small')
				);
			}
			$webglobal['dataarray'][$tempdata['id']] = $tempdata;
		}
	}
}
//我收藏的商家
elseif ($webglobal['action']=='favoritecom')
{
	$webrequest['delid'] = isset($webrequest['delid']) ? intval($webrequest['delid']) : 0;
	if ($webrequest['delid'] > 0)
	{
		$webglobal['datainfo'] = $db->GetOne("SELECT * FROM {$webconfig['dbpre']}company_favorites WHERE id='{$webrequest['delid']}' AND user_id='{$user['base_uid']}'");
		if (empty($webglobal['datainfo']))
		{
			global_ShowMessage("参数错误。");
		}
		$db->Delete('company_favorites', "id='{$webrequest['delid']}'");
		$db->Update('company', "favorites_num=favorites_num-1", "id='{$webglobal['datainfo']['company_id']}' AND favorites_num>0");
		global_ShowMessage("恭喜您，删除成功。", WEBURLPATH."/my.php?action={$webglobal['action']}&page={$webrequest['page']}");
	}

	$webglobal['perpage'] = 10;
	$tempsearchsql = " WHERE F.user_id='{$user['base_uid']}'";
	$webglobal['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}company_favorites F{$tempsearchsql}");
	if ($webglobal['datanum']>0)
	{
		$webglobal['page'] = global_Page($webglobal['datanum'], $webglobal['perpage'], $webrequest['page'], WEBURLPATH."/my.php?action={$webglobal['action']}&page=@@");
		$tempstartnum = ($webrequest['page']-1)*$webglobal['perpage'];
		$query = $db->Query("SELECT F.*,C.name AS c_name,C.logo AS c_logo FROM {$webconfig['dbpre']}company_favorites F LEFT JOIN {$webconfig['dbpre']}company C ON F.company_id=C.id{$tempsearchsql} ORDER BY F.id DESC LIMIT $tempstartnum, {$webglobal['perpage']}");
		$webglobal['dataarray'] = array();
		while ($tempdata = $db->FetchArray($query))
		{
			$tempdata['addtime_show'] = global_FormatTime($tempdata['addtime']);
			$webglobal['dataarray'][$tempdata['id']] = $tempdata;
		}
	}
}
//我的积分
elseif ($webglobal['action']=='credit')
{
	$webglobal['integral_status'] = array(0=>'待审核',1=>'审核通过',2=>'发货',3=>'用户确认收货');
	$webglobal['perpage'] = 10;
	$tempsearchsql = " WHERE R.user_id='{$user['base_uid']}'";
	$webglobal['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}integral_order R{$tempsearchsql}");
	if ($webglobal['datanum']>0)
	{
		$webglobal['page'] = global_Page($webglobal['datanum'], $webglobal['perpage'], $webrequest['page'], WEBURLPATH."/my.php?action=credit&page=@@");
		$tempstartnum = ($webrequest['page']-1)*$webglobal['perpage'];
		$query = $db->Query("SELECT R.*,G.name AS g_name,G.image AS g_image, G.description as g_description FROM {$webconfig['dbpre']}integral_order R LEFT JOIN {$webconfig['dbpre']}integral_goods G ON R.integral_goods_id=G.id{$tempsearchsql} ORDER BY R.id DESC LIMIT $tempstartnum, {$webglobal['perpage']}");
		$webglobal['dataarray'] = array();
		while ($tempdata = $db->FetchArray($query))
		{
			$tempdata['addtime_show'] = global_FormatTime($tempdata['addtime']);
			$tempdata['g_description'] = global_CutStr($tempdata['g_description'], 200);
			if ($tempdata['g_image']) {
				$tempdata['thumbnail'] = array(
					'big' => getThumbnails($tempdata['g_image'], 'big'),
					'small' => getThumbnails($tempdata['g_image'], 'small')
				);
			}
			$webglobal['dataarray'][$tempdata['id']] = $tempdata;
		}
	}
} elseif ($webglobal['action']=='password') {
	if (isset($webrequest['check']))
	{
		global_CheckPost(
			array(
				array('passwordold','password','','旧密码输入错误',0,''),
				array('password','password','','新密码至少为6位',0,''),
				array('passwordtwo','password','','新密码重复至少为6位',0,''),
		));

		if (empty($webglobal['CPM']))
		{
			if ($webglobal['CPP']['password']!='')
			{
				if (global_Md5($webglobal['CPP']['passwordold'])!=$user['pwd'])
				{
					$webglobal['CPM']['passwordold'] = '旧密码输入错误';
				}
				elseif ($webglobal['CPP']['password']!=$webglobal['CPP']['passwordtwo'])
				{
					$webglobal['CPM']['passwordtwo'] = '两次输入的密码不一样';
				}
				else
				{
					$webglobal['CPD']['pwd'] = global_Md5($webglobal['CPP']['password']);
				}
			}
			
		}

		if (!empty($webglobal['CPM']))
		{
			global_ShowMessage($webglobal['CPM'], '', 'BACK');
		}
		else
		{
			$db->Update('user', '', "id='{$user['id']}'");
			if (isset($webglobal['CPD']['pwd']))
			{
				$usercheckobj->SetUserCookie($user['id'], $webglobal['CPD']['pwd'], 0);
			}
			global_ShowMessage("恭喜您，密码修改成功！", WEBURLPATH."/my.php?action=password");
		}
	}

} elseif ($webglobal['action']=='auth') {
	$webrequest['type'] = isset($webrequest['type']) ? trim($webrequest['type']) : 'email';
	if (!in_array($webrequest['type'], array('email', 'idcode', 'mobil'))) {
		global_ShowMessage("参数错误！", WEBURLPATH."/my.php?action=auth");
	}

	if ($webrequest['type'] == 'email') {
		
	} elseif ($webrequest['type'] == 'mobil') {
		
	} elseif ($webrequest['type'] == 'idcode') {
		if (isset($webrequest['check'])) {
			global_CheckPost(
				array(
					array('indentitycard,','idcard','','身份证号码错误'),
			));

			if (empty($webglobal['CPM'])) {
				if ($webglobal['CPP']['indentitycard']!='' && !global_CheckIdCard($webglobal['CPP']['indentitycard'], '', isset($user['birthday']) ? $user['birthday'] : '', $user['gender']))
				{
					$webglobal['CPM']['indentitycard'] = '身份证号码错误';
				}
				
			}
			if (empty($webglobal['CPM'])) {
				if (!checkIdCode($webglobal['CPP']['indentitycard'])) {
					$webglobal['CPM'][] = '身份验证失败，请重新确认身份证号码';
				} else {
					$webglobal['CPD']['auth_indentity'] = 1;
					if ($user['auth_tel'] == 1) {
						$webglobal['CPD']['status'] = 1;
					}
					$db->Update('user', '', "id='{$user['id']}'");
					global_ShowMessage("恭喜您，身份认证通过！", WEBURLPATH."/my.php?action=auth&type=idcode");
				}
			}
			
		}
	}
} elseif ($webglobal['action']=='avatar') {
	$webglobal['imagepath'] = '/upfiles/user/'.global_FormatTime(0, 'Ym');
	$webglobal['avatarsetting'] = array('type'=>array('gif', 'jpg', 'jpeg', 'png', 'bmp'), 'size'=>2097152);
	if (isset($webrequest['cutpic']))
	{
		include WEBFILEPATH.'/include/image.class.php';
		$tempimage = new Image($webrequest['picabspath']);
		$resizearray = array(
			'imageWidth' => $webrequest['img_w'],
			'imageHeight' => $webrequest['img_h'],
			'dstX' => $webrequest['dst_x'],
			'dstY' => $webrequest['dst_y'],
			'srcX' => $webrequest['src_x'],
			'srcY' => $webrequest['src_y'],
			'dstWidth' => $webrequest['dst_w'],
			'dstHeight' => $webrequest['dst_h'],
			'srcWidth' => $webrequest['src_w'],
			'srcHeight' => $webrequest['src_h'],
			'bgcolor' => '#ffffff',
			);
		$tempimage->SetResizePlace($resizearray);
		$tempimage->Resize();
		if ($tempimage->SaveFile($webrequest['spicabspath']))
		{
			echo 'resultstatus=1&errmsg=';
		}
		else
		{
			echo 'resultstatus=0&errmsg='.urlencode('error!');
		}
		exit();
	}
	if (isset($webrequest['check']))
	{
		include WEBFILEPATH.'/include/upload.class.php';
		$templogoupload = new Upload('avatar', $webglobal['avatarsetting']);
		if (!$templogoupload->CheckFile())
		{
			$webglobal['CPM']['avatar'] = '头像图片: '.$templogoupload->errorMsg;
			global_ShowMessage($webglobal['CPM'], '', 'BACK');
		}
		else
		{
			if ($templogoupload->CheckFile())
			{
				$templogoupload->SaveFile(WEBFILEPATH.$webglobal['imagepath']);
				@copy(WEBFILEPATH.$webglobal['imagepath'].'/'.$templogoupload->fileList[0]['name'], WEBFILEPATH.$webglobal['imagepath'].'/s_'.$templogoupload->fileList[0]['name']);
				$webglobal['CPD']['avatar'] = $webglobal['imagepath'].'/s_'.$templogoupload->fileList[0]['name'];
				$webglobal['oldavatar'] = $webglobal['imagepath'].'/'.$templogoupload->fileList[0]['name'];
				if ($user['avatar'] != '')
				{
					@unlink(WEBFILEPATH.$user['avatar']);
					@unlink(WEBFILEPATH.dirname($user['avatar']).'/'.substr(basename($user['avatar']), 2));
				}
			}

			$db->Update('user', '', "id='{$user['id']}'");
			if (isset($webglobal['CPD']['pwd']))
			{
				$usercheckobj->SetUserCookie($user['id'], $webglobal['CPD']['pwd'], 0);
			}
			$webglobal['picwidth'] = $webglobal['picheight'] = 120;
			$webglobal['flashVars'] = "hostpath=".urlencode(WEBURLPATH."/my.php?action=avatar&cutpic")."&picurl=".urlencode(WEBURLPATH.$webglobal['oldavatar'])."&picabspath=".urlencode(WEBFILEPATH.$webglobal['oldavatar'])."&spicabspath=".urlencode(WEBFILEPATH.$webglobal['CPD']['avatar'])."&spicwidth={$webglobal['picwidth']}&spicheight={$webglobal['picheight']}&funcvar=".urlencode("ChangePic:simgshow,".WEBURLPATH."{$webglobal['CPD']['avatar']}");
			//global_ShowMessage("恭喜您，头像上传成功！", WEBURLPATH."/my.php?action=avatar");
		}
	}
//个人信息
} else {
	$user['signhtml'] = str_replace("<br />", "\n", $user['signhtml']);
	$user['interests'] = explode(",", $user['interests']);
	$user['birth_address'] = $user['birth_address'] ? unserialize($user['birth_address']) : array('id_list'=>array(),'area_text'=>array());
	$user['birth_address']['id_list'] = implode(',', $user['birth_address']['id_list']);
	$user['birth_address']['area_text'] = implode(',', $user['birth_address']['area_text']);
	if ($user['birthday']=='0000-00-00') {
		$user['birthday'] = explode('-', $user['birthday']);
	} else {
		$user['birthday'] = explode('-', $user['birthday']);
	}
	$webcache['setting']['user_interests'] = global_Trim(explode("\n", $webcache['setting']['user_interests']));
	$webglobal['imagepath'] = '/upfiles/user/'.global_FormatTime(0, 'Ym');
	$webglobal['avatarsetting'] = array('type'=>array('gif', 'jpg', 'jpeg', 'png', 'bmp'), 'size'=>2097152);

	$webglobal['birthday_num'] = array(
		'birthday_year' => array(),
		'birthday_month' => array(),
		'birthday_day' => array()
	);

	for ($i=1910;$i<=2020;$i++) {
		$webglobal['birthday_num']['birthday_year'][] = $i;
	}
	for ($i=1;$i<=12;$i++) {
		$webglobal['birthday_num']['birthday_month'][] = $i;
	}
	for ($i=1;$i<=31;$i++) {
		$webglobal['birthday_num']['birthday_day'][] = $i;
	}

	if (isset($webrequest['check']))
	{
		include WEBFILEPATH.'/include/upload.class.php';
		global_CheckPost(
				array(
					array('gender,','int','','',0,0),
					array('birthday_year','int','','',0,0),
					array('birthday_month','int','','',0,0),
					array('birthday_day','int','','',0,0),
					array('birthday,','date','','出生日期必须为日期格式'),
					array('birthday_address[]','int','',''),
					array('birthday_address_name','str','',''),
					array('truename,','str','','',0,''),
					array('indentitycard,','idcard','','身份证号码错误'),
					array('tel,','mobile','','手机号码错误'),
					array('nickname,','nickname','','昵称不能为空',1),
					array('signhtml,','str','','',0,''),
					array('interests[]','str','','',0,''),
					array('other_interest,','str','','',0,''),
					//array('passwordold','password','','旧密码输入错误',0,''),
					//array('password','password','','新密码至少为6位',0,''),
					//array('passwordtwo','password','','新密码重复至少为6位',0,''),
			));
		if (empty($webglobal['CPM'])) {
			/*
			if ($webglobal['CPP']['indentitycard']!='' && !global_CheckIdCard($webglobal['CPP']['indentitycard'], '', isset($webglobal['CPP']['birthday']) ? $webglobal['CPP']['birthday'] : '', $webglobal['CPP']['gender']))
			{
				$webglobal['CPM']['indentitycard'] = '身份证号码错误';
			}
			*/
			/*
			if ($webglobal['CPP']['password']!='')
			{
				if (global_Md5($webglobal['CPP']['passwordold'])!=$user['pwd'])
				{
					$webglobal['CPM']['passwordold'] = '旧密码输入错误';
				}
				elseif ($webglobal['CPP']['password']!=$webglobal['CPP']['passwordtwo'])
				{
					$webglobal['CPM']['passwordtwo'] = '两次输入的密码不一样';
				}
				else
				{
					$webglobal['CPD']['pwd'] = global_Md5($webglobal['CPP']['password']);
				}
			}
			*/
			if (strlen($webglobal['CPP']['nickname']) > 20) {
				$webglobal['CPM']['nickname'] = '昵称输入超出范围';
			}

			$birthday_address = array(
				'id_list' => array(),
				'area_text' => array()
			);
			if (isset($webglobal['CPP']['birthday_address']) && $webglobal['CPP']['birthday_address'])
			{
				$birthday_address_name = explode(',', $webglobal['CPP']['birthday_address_name']);
				foreach ($webglobal['CPP']['birthday_address'] as $key => $listid) {
					if ($listid) {
						$birthday_address['id_list'][] = $listid;
						$birthday_address['area_text'][] = isset($birthday_address_name[$key]) ? $birthday_address_name[$key] : '';
					} else {
						break;
					}
				}
				$webglobal['CPD']['birth_address'] = serialize($birthday_address);
			}
		}

		if (empty($webglobal['CPM']) && $webglobal['CPP']['birthday_month'] && $webglobal['CPP']['birthday_day'] && $webglobal['CPP']['birthday_year']) {
			if (checkdate($webglobal['CPP']['birthday_month'], $webglobal['CPP']['birthday_day'], $webglobal['CPP']['birthday_year'])) {
				$webglobal['CPD']['birthday'] = $webglobal['CPP']['birthday_year'] . '-' . $webglobal['CPP']['birthday_month'] . '-' . $webglobal['CPP']['birthday_day'];
			} else {
				$webglobal['CPM']['birthday_error'] = '请选择正确的出生日期';
			}
		}
		/*
		if (empty($webglobal['CPM']))
		{
			$templogoupload = new Upload('avatar', $webglobal['avatarsetting']);
			if (!$templogoupload->CheckFile() && !$templogoupload->isNone)
			{
				$webglobal['CPM']['avatar'] = '头像图片: '.$templogoupload->errorMsg;
			}
		}
		*/
		if (!empty($webglobal['CPM']))
		{
			global_ShowMessage($webglobal['CPM'], '', 'BACK');
		}
		else
		{
			$webglobal['CPD']['interests'] = implode(',', $webglobal['CPP']['interests']);
			$webglobal['CPD']['other_interest'] = $webglobal['CPP']['other_interest'];
			$webglobal['CPD']['signhtml'] = global_ConvNewline($webglobal['CPD']['signhtml']);
			/*
			if ($templogoupload->CheckFile())
			{
				$templogoupload->SaveFile(WEBFILEPATH.$webglobal['imagepath']);
				$webglobal['CPD']['avatar'] = $webglobal['imagepath'].'/'.$templogoupload->fileList[0]['name'];
				if ($user['avatar'] != '')
				{
					@unlink(WEBFILEPATH.$user['avatar']);
				}
			}
			*/
			$db->Update('user', '', "id='{$user['id']}'");
			if (isset($webglobal['CPD']['pwd']))
			{
				$usercheckobj->SetUserCookie($user['id'], $webglobal['CPD']['pwd'], 0);
			}
			global_ShowMessage("恭喜您，资料更新成功！", WEBURLPATH."/my.php");
		}
	}
}

function checkIdCode($code) {
	global $user;
	$url = AUTH_IDCODE_URL . $code;
	$parser = new IDCodeXMLDataParser();
	if (!$data = $parser->getData($url)) {
		return false;
	}

	$preg_pattern = array(
		'province' => '',
		'city'     => '',
	);

	if (isset($user['birth_address']) && $user['birth_address'] != '') {
		$userLocation = unserialize($user['birth_address']);
		if (!isset($userLocation['area_text'][0]) || !isset($userLocation['area_text'][1]) || !$userLocation['area_text'][0] || !$userLocation['area_text'][1]) {
			return false;
		} else {
			//get the province
			if (preg_match('/^(.*)(?:省|市|自治区)$/ies', $userLocation['area_text'][0], $matches)) {
				if (isset($matches[1]) && $matches[1] != '') {
					$preg_pattern['province'] = $matches[1];
				} else {
					return false;
				}
			} else {
				return false;
			}

			//get the city
			if (preg_match('/^(.*?)(?:市|区|自治州|$)/ies', $userLocation['area_text'][1], $matches)) {
				if (isset($matches[1]) && $matches[1] != '') {
					$preg_pattern['city'] = $matches[1];
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
	} else {
		return false;
	}

	if (isset($user['birthday']) && $user['birthday'] != '') {
		$strBirthDay = implode('', explode('-', $user['birthday']));
		if ($strBirthDay != $data['BIRTHDAY']) {
			return false;
		}
	} else {
		return false;
	}

	if ($preg_pattern && isset($data['LOCATION']) && $data['LOCATION'] != '') {
		foreach ($preg_pattern as $value) {
			if (stripos($data['LOCATION'], $value) === false) {
				return false;
			}
		}
		return true;
	}

	return false;
}

template_Display('my');

class IDCodeXMLDataParser {

	protected $encoding = 'utf-8';
	protected $item = array();
	protected $data = '';
	protected static $startElements=array(
		'CODE', 'LOCATION', 'BIRTHDAY', 'GENDER');


	public function setEncoding($encoding) {
		$this->encoding = $encoding;
	}

	public function getData($url) {
		if ($contents = file_get_contents($url)) {
			$this->parseData($contents);
		}
		return $this->item;
	}

	public function startElement($xml_parser, $name, $attribs) {
		$this->data = '';
		if (in_array($name, self::$startElements)) {
			$this->item[$name] = '';
		}
	}

	public function endElement($xml_parser, $name) {
		if (in_array($name, self::$startElements) && isset($this->item[$name])) {
			$this->item[$name] = $this->data;
		}
	}

	protected function characterData($xml_parser, $data) {
		$this->data .= $data;
	}

	public function parseData($contents) {
		$xml_parser = xml_parser_create();
		xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
		xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, true);

		$encoding = xml_parser_get_option($xml_parser, XML_OPTION_TARGET_ENCODING);
		xml_set_element_handler($xml_parser, array($this,"startElement"), array($this,"endElement"));
		xml_set_character_data_handler($xml_parser, array($this,"characterData"));

		if (!xml_parse($xml_parser, $contents)) {
			throw new Exception(sprintf("XML error: %s at line %d",
						xml_error_string(xml_get_error_code($xml_parser)),
						xml_get_current_line_number($xml_parser)));
		}
		xml_parser_free($xml_parser);
		//$this->setTotalItems(count($this->items));
		//return $this->items;
	}
}
